// 创建 Toast 容器
function createToastContainer() {
    let container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.style.cssText = `
            position: fixed;
            top: 0;
            right: 0;
            padding: 1rem;
            z-index: 9999;
            max-width: 90%;
        `;
        document.body.appendChild(container);
    }
    return container;
}

// 自定义 Toast 类
class CustomToast {
    constructor(element, options = {}) {
        this.element = element;
        this.options = {
            autohide: options.autohide !== undefined ? options.autohide : true,
            delay: options.delay !== undefined ? options.delay : 3000
        };
        this.timer = null;
    }
    
    show() {
        // 添加显示类
        this.element.classList.add('toast-show');
        
        // 如果启用自动隐藏
        if (this.options.autohide) {
            this.timer = setTimeout(() => {
                this.hide();
            }, this.options.delay);
        }
    }
    
    hide() {
        // 清除计时器
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
        
        // 添加隐藏类
        this.element.classList.remove('toast-show');
        this.element.classList.add('toast-hide');
        
        // 动画结束后移除元素
        setTimeout(() => {
            // 触发隐藏事件
            const event = new CustomEvent('hidden.toast');
            this.element.dispatchEvent(event);
            
            // 从DOM中移除
            if (this.element.parentNode) {
                this.element.parentNode.removeChild(this.element);
            }
        }, 300); // 与CSS过渡时间匹配
    }
}

// 显示 Toast 提示
function showToast(message, type = 'info') {
    // 添加Toast样式
    addToastStyles();
    
    const container = createToastContainer();
    const toast = document.createElement('div');
    
    // 设置 Toast 类型对应的颜色
    const typeColors = {
        'success': '#198754',
        'error': '#dc3545', 
        'warning': '#ffc107',
        'info': '#0dcaf0',
        'loading': '#0d6efd'
    };
    
    const bgColor = typeColors[type] || typeColors.info;
    
    toast.className = 'custom-toast';
    toast.style.backgroundColor = bgColor;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    // 创建内部结构
    const toastContent = document.createElement('div');
    toastContent.style.cssText = 'display: flex; align-items: center;';
    
    const toastBody = document.createElement('div');
    toastBody.className = 'toast-body';
    toastBody.textContent = message;
    toastBody.style.cssText = 'flex: 1; margin: 0.75rem; color: white;';
    
    const closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'toast-close-btn';
    closeBtn.setAttribute('aria-label', 'Close');
    closeBtn.style.cssText = `
        margin-right: 0.75rem;
        background: none;
        border: none;
        color: white;
        font-size: 1.5rem;
        line-height: 1;
        cursor: pointer;
        opacity: 0.75;
        transition: opacity 0.15s ease-in-out;
    `;
    closeBtn.innerHTML = '&times;';
    
    // 添加关闭事件
    closeBtn.addEventListener('click', () => {
        const toastInstance = new CustomToast(toast);
        toastInstance.hide();
    });
    
    toastContent.appendChild(toastBody);
    toastContent.appendChild(closeBtn);
    toast.appendChild(toastContent);
    
    container.appendChild(toast);
    
    // 初始化并显示Toast
    const toastInstance = new CustomToast(toast, {
        autohide: true,
        delay: 3000
    });
    
    toastInstance.show();
    
    // 监听隐藏事件
    toast.addEventListener('hidden.toast', () => {
        // 可以在这里添加额外的隐藏处理逻辑
    });
}

// 添加Toast样式
function addToastStyles() {
    // 检查样式是否已存在
    if (document.getElementById('toast-styles')) {
        return;
    }
    
    const style = document.createElement('style');
    style.id = 'toast-styles';
    style.textContent = `
        .custom-toast {
            position: relative;
            min-width: 280px;
            margin-bottom: 0.75rem;
            border-radius: 0.25rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            transform: translateX(100%);
            opacity: 0;
            transition: transform 0.3s ease-out, opacity 0.3s ease-out;
        }
        
        .custom-toast.toast-show {
            transform: translateX(0);
            opacity: 1;
        }
        
        .custom-toast.toast-hide {
            transform: translateX(100%);
            opacity: 0;
        }
        
        .toast-close-btn:hover {
            opacity: 1 !important;
        }
    `;
    document.head.appendChild(style);
}

// 创建全局 Loading
let currentLoadingTimeout = null;

// 自定义加载动画类
class CustomSpinner {
    constructor(element) {
        this.element = element;
        this.setupSpinner();
    }
    
    setupSpinner() {
        // 清空元素
        this.element.innerHTML = '';
        this.element.classList.add('custom-spinner');
        
        // 创建旋转环
        const spinnerRing = document.createElement('div');
        spinnerRing.className = 'spinner-ring';
        
        this.element.appendChild(spinnerRing);
    }
}

function createLoadingContainer() {
    let container = document.getElementById('global-loading-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'global-loading-container';
        container.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        const loadingContent = document.createElement('div');
        loadingContent.className = 'loading-content';
        loadingContent.style.cssText = `
            background: white;
            padding: 2rem;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            max-width: 80%;
            transform: translateY(20px);
        `;
        
        // 创建自定义spinner
        const spinner = document.createElement('div');
        spinner.className = 'custom-spinner-container';
        
        // 创建文本元素
        const loadingText = document.createElement('div');
        loadingText.id = 'loading-text';
        loadingText.style.cssText = `
            margin-top: 0.5rem;
            color: #566a7f;
            font-size: 1rem;
        `;
        
        // 初始化spinner
        new CustomSpinner(spinner);
        
        loadingContent.appendChild(spinner);
        loadingContent.appendChild(loadingText);
        container.appendChild(loadingContent);
        document.body.appendChild(container);
        
        // 添加样式
        addLoadingStyles();
        
        // 应用动画
        setTimeout(() => {
            loadingContent.style.transition = 'transform 0.3s ease';
            loadingContent.style.transform = 'translateY(0)';
        }, 10);
    }
    return container;
}

// 显示 Loading
function showLoading(text = '加载中...') {
    // 如果有正在显示的 loading，先清除
    if (currentLoadingTimeout) {
        clearTimeout(currentLoadingTimeout);
        currentLoadingTimeout = null;
    }
    
    const container = createLoadingContainer();
    const loadingText = document.getElementById('loading-text');
    
    // 更新文本
    loadingText.textContent = text;
    
    // 显示 loading
    container.style.display = 'flex';
    
    // 禁用页面滚动
    document.body.style.overflow = 'hidden';
    
    // 添加淡入效果
    currentLoadingTimeout = setTimeout(() => {
        container.style.opacity = '1';
    }, 10);
}

// 隐藏 Loading
function hideLoading() {
    const container = document.getElementById('global-loading-container');
    if (container) {
        // 清除可能存在的 timeout
        if (currentLoadingTimeout) {
            clearTimeout(currentLoadingTimeout);
            currentLoadingTimeout = null;
        }
        
        // 添加淡出效果
        container.style.opacity = '0';
        
        // 延迟后完全隐藏
        setTimeout(() => {
            container.style.display = 'none';
            // 恢复页面滚动
            document.body.style.overflow = '';
        }, 300);
    }
}

// 添加加载样式
function addLoadingStyles() {
    // 检查样式是否已存在
    if (document.getElementById('loading-styles')) {
        return;
    }
    
    const style = document.createElement('style');
    style.id = 'loading-styles';
    style.textContent = `
        /* 自定义spinner样式 */
        .custom-spinner-container {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 3rem;
            height: 3rem;
            margin: 0 auto;
        }
        
        .custom-spinner {
            display: inline-block;
            width: 3rem;
            height: 3rem;
        }
        
        .spinner-ring {
            position: absolute;
            width: 3rem;
            height: 3rem;
            border: 0.25rem solid rgba(0, 123, 255, 0.1);
            border-radius: 50%;
            border-top-color: #0d6efd;
            animation: spinner-spin 0.75s linear infinite;
        }
        
        @keyframes spinner-spin {
            to { transform: rotate(360deg); }
        }
        
        /* 加载内容动画 */
        .loading-content {
            animation: slideUp 0.3s ease forwards;
        }
        
        @keyframes slideUp {
            to {
                transform: translateY(0);
            }
        }
    `;
    document.head.appendChild(style);
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    // 确保样式已添加
    addToastStyles();
    addLoadingStyles();
});